package com.example.deviceinfo.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.deviceinfo.data.model.DeviceInfo
import com.example.deviceinfo.data.repository.DeviceInfoRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class DeviceInfoViewModel @Inject constructor(
    private val repository: DeviceInfoRepository
) : ViewModel() {
    private val _deviceList = MutableLiveData<Resource<List<DeviceInfo>>>()
    val deviceList: LiveData<Resource<List<DeviceInfo>>> = _deviceList

    fun fetchDevices(page: Int, isRefresh: Boolean = false) {
        viewModelScope.launch {
            _deviceList.value = Resource.Loading()
            try {
                val response = repository.fetchDevices(page)
                if (response.isSuccessful) {
                    val paginationResponse = response.body()
                    if (paginationResponse != null && paginationResponse.code == 200) {
                        // 设备数组在 paginationResponse.data.data 中
                        _deviceList.value = Resource.Success(paginationResponse.data.data)
                    } else {
                        _deviceList.value =
                            Resource.Error("API 错误: ${paginationResponse?.msg ?: "未知错误"}")
                    }
                } else {
                    _deviceList.value = Resource.Error("请求失败: ${response.code()}")
                }
            } catch (e: Exception) {
                _deviceList.value = Resource.Error("网络错误: ${e.message}")
            }
        }
    }
}

// 优化后的资源状态封装类
sealed class Resource<T>(
    val data: T? = null,
    val message: String? = null,
    val isInitialLoad: Boolean = false,
    val isRefresh: Boolean = false
) {
    class Success<T>(
        data: T,
        isRefresh: Boolean = false
    ) : Resource<T>(data, isRefresh = isRefresh)

    class Error<T>(
        message: String,
        data: T? = null,
        isRefresh: Boolean = false
    ) : Resource<T>(data, message, isRefresh = isRefresh)

    class Loading<T>(
        data: T? = null,
        isInitialLoad: Boolean = false,
        isRefresh: Boolean = false
    ) : Resource<T>(data, isInitialLoad = isInitialLoad, isRefresh = isRefresh)
}